﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CrmContacto.Contracts;
using Web.Framework;
using Web.Framework.Svc;
using CrmContacto.Contracts.Contracts.Search;
using Web.PuntoDeVenta.Code;
using Web.Framework.Translate;
using CrmContacto.Contracts.Contracts;
using CrmContacto.Contracts.Enums;

namespace Web.PuntoDeVenta.App
{
    public partial class CustomerBitacora : System.Web.UI.Page, IWebMessage
    {
        private Cliente currentCliente
        {
            get
            {
                return (Cliente)(ViewState["currentCliente"]);
            }
            set
            {
                ViewState["currentCliente"] = value;
            }
        }

        private ExceptionManager ExceptionManager = new ExceptionManager();

        protected void Page_Load(object sender, EventArgs e)
        {
            ExceptionManager.WebMessager = this;
            try
            {
                if (!this.IsPostBack)
                {
                    if (this.Request["Id"] == null)
                        throw new ArgumentNullException("Id");

                    int customerId = Convert.ToInt32(this.Request.QueryString["Id"]);

                    ServiceOptions options = new ServiceOptions();
                    ClienteByIdOptions clientOptions = new ClienteByIdOptions();
                    clientOptions.LoadBitacora = true;
                    clientOptions.DesdePdv = null;
                    currentCliente = WebServiceHelper.GetCustomerById(options, customerId, clientOptions);

                    LoadCbos();
                    Bind();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.HandleException(ex);
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            if(currentCliente != null && currentCliente.Estado == (int)EstadoCliente.Inactivo)
            {
                pnlCustomerControlsBitacoraForEdit.Enabled = false;
                lnkGuardar.Enabled = false;
            }

            base.OnPreRender(e);
        }

        private void LoadCbos()
        {
            var tipoMensajeBitacoraList = WebServiceHelper.GetTipoMensajeBitacora(new TipoMensajeBitacoraSearch() { EmpresaId = BaseMasterPage.CompanyId, EsPdv = true });
            UIHelper.LoadCbo(tipoMensajeBitacoraList, cboTipoMensajeBitacoraId, string.Empty);
        }

        private void Bind()
        {            
            this.txtAccion.Text = string.Empty;

            UIHelper.LoadEstados<TipoRegistroBitacora>(this.cboTipoRegistroBitacora);
            this.cboTipoRegistroBitacora.SelectedValue = ((int)TipoRegistroBitacora.Mensaje).ToString();
            this.cboTipoRegistroBitacora.Enabled = false;

            BindBitacoraToGrid();
        }

        protected void lnkGuardar_Click(object sender, EventArgs e)
        {
            try
            {
                SaveBitacoraRegistry();
                Bind();
                ShowMessage(LocalizationProvider.Instance["Bo.Messages.MensajeSaveExitoso"], WebMessageType.Notification);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }        

        private void BindBitacoraToGrid()
        {
            this.GridBitacora.DataSource = currentCliente.Bitacora;
            this.GridBitacora.DataBind();
        }

        private void SaveBitacoraRegistry()
        {
            ClienteBitacora clienteBitacora = new ClienteBitacora();
            clienteBitacora.TipoRegistroBitacora = UIHelper.GetIntFromInputCbo(this.cboTipoRegistroBitacora).Value;
            clienteBitacora.Accion = this.txtAccion.Text;
            clienteBitacora.ContactoId = currentCliente.Id;
            clienteBitacora.FechaCreacion = DateTime.Now;
            clienteBitacora.TipoMensajeBitacoraId = UIHelper.GetIntFromInputCbo(this.cboTipoMensajeBitacoraId).Value;

            List<string> ptoVta = HttpHelper.GetCookieValues(HttpHelper.cookiePtoVtaName, this.Request);
            clienteBitacora.PuntoDeVentaId = Convert.ToInt32(ptoVta[0]);

            ServiceOptions options = new ServiceOptions();
            options.CompanyId = BaseMasterPage.CompanyId;
            options.UserName = BaseMasterPage.UserName;
            WebServiceHelper.SaveCustomerBitacora(options, clienteBitacora);

            currentCliente.Bitacora.Add(clienteBitacora);
        }

        protected void GridBitacora_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "editar")
                {
                    //    int temporadaId = Convert.ToInt32(this.GridTemporadas.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    //    this.Response.Redirect(string.Format("/App/TemporadaEdit.aspx?Id={0}", temporadaId), true);
                }
                else if (e.CommandName == "eliminar")
                {
                    //int temporadaId = Convert.ToInt32(this.GridTemporadas.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    //WebServiceHelper.EliminarTemporada(temporadaId);
                    //StoreHelper.GetObject(this.Session, MiscClass.CustomerSearchCacheKey);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridBitacora_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                this.GridBitacora.PageIndex = e.NewPageIndex;
                BindBitacoraToGrid();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private List<TipoMensajeBitacora> tipoMensajeBitacoraList;
        private List<TipoMensajeBitacora> GetTipoMensajeBitacora()
        {
            if (tipoMensajeBitacoraList == null)
            {
                tipoMensajeBitacoraList = WebServiceHelper.GetTipoMensajeBitacora(new TipoMensajeBitacoraSearch() { EmpresaId = BaseMasterPage.CompanyId, EsPdv = true });
            }

            return tipoMensajeBitacoraList;
        }

        protected void GridBitacora_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    ClienteBitacora clienteBitacoraItem = (ClienteBitacora)e.Row.DataItem;
                    e.Row.Cells[1].Text = UIHelper.GetEnumDescription((TipoRegistroBitacora)clienteBitacoraItem.TipoRegistroBitacora);
                    if (clienteBitacoraItem.TipoMensajeBitacoraId.HasValue)
                    {
                        e.Row.Cells[2].Text = GetTipoMensajeBitacora().Where(r => r.Id == clienteBitacoraItem.TipoMensajeBitacoraId.Value).Single().Nombre;
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
       
        public void ShowMessage(string message, WebMessageType type)
        {
            ShowMessage("Mensaje", message, type);
        }

        public void ShowMessage(string title, string message, WebMessageType type)
        {
            this.pnlMessages.CssClass = "pnlMessagesClass displayBlock";
            this.txtErrorTitle.Text = title;
            this.txtMessages.Text = message;
            if (type != WebMessageType.Error)
            {
                pnlError.CssClass = "errorPanelMessage";
            }
            else
            {
                pnlError.CssClass = "errorPanelError";
            }
        }
    }
}